import os
import signal
import sys
import time
from dotenv import load_dotenv
from loguru import logger

from src.utils import setup_logger
from src.core import get_processor
from src.mcp import MCPServer

# 加载环境变量
load_dotenv()

# 设置日志
setup_logger()

def request_handler(request_data):
    """处理客户端请求的回调函数"""
    processor = get_processor()
    return processor.process_request(request_data)

def signal_handler(sig, frame):
    """处理终止信号"""
    logger.info("接收到终止信号，正在关闭服务...")
    if server:
        server.stop()
    
    # 关闭处理器
    processor = get_processor()
    processor.close()
    
    logger.info("服务已安全关闭")
    sys.exit(0)

if __name__ == "__main__":
    # 注册信号处理器
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    # 创建并启动MCP服务器
    server = MCPServer(request_handler)
    
    # 获取服务器配置
    host = os.getenv("MCP_HOST", "localhost")
    port = int(os.getenv("MCP_PORT", "8080"))
    
    logger.info(f"正在启动智能SQL数据库助手服务，监听 {host}:{port}...")
    
    if server.start():
        logger.success(f"服务已启动，等待客户端连接...")
        
        try:
            # 保持主线程运行
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            pass
        finally:
            server.stop()
            
            # 关闭处理器
            processor = get_processor()
            processor.close()
            
            logger.info("服务已安全关闭")
    else:
        logger.error("服务启动失败")
        sys.exit(1) 